<template>
  <div class="login-container">
    <div class="login-box">
      <el-form ref="formRef" :rules="data.rules" :model="data.form" class="login-form" destroy-on-close >
        <h2 style="text-align: center; color: #fff; margin-bottom: 30px; color: black ">注册</h2>

        <el-form-item prop="username">
          <el-input
              v-model="data.form.username"
              placeholder="用户名"
              prefix-icon="User"
              clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="data.form.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
          ></el-input>
        </el-form-item>

        <el-form-item prop="dbpassword">
          <el-input
              v-model="data.form.dbpassword"
              type="password"
              placeholder="确认密码"
              prefix-icon="Lock"
              show-password
          ></el-input>
        </el-form-item>

        <el-form-item prop="role">
          <el-select
              v-model="data.form.role"
              placeholder="选择角色"
              style="width: 100%"
          >
            <el-option label="评委" value="JUDGE" />
            <el-option label="参赛者" value="PARTICIPANT" />
          </el-select>
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
              v-model="data.form.phone"
              placeholder="电话"
              prefix-icon="Iphone"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
              v-model="data.form.email"
              placeholder="邮箱"
              prefix-icon="Message"
              clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
          >
            登录
          </el-button>
          <el-button
              type="success"
              class="login-btn"
              @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import { ElMessage } from 'element-plus';
import request from "@/utils/request.js";
import router from "@/router/index.js";

const data = reactive({
  form: {
    username: '',
    password: '',
    dbpassword: '',
    email: '',
    phone: '',
    role: ''
  },
  rules:{
    username:[
      {required: true,message: '请输入姓名',trigger:['blur', 'change']},
      { min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur' }
    ],
    password:[
      {required: true,message: '请输入密码',trigger:['blur', 'change']},
      { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' },
      { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,20}$/,
        message: '需包含大小写字母和数字（6-20位）'
      }
    ],
    dbpassword:[
      {required: true,message: '请输入密码',trigger:['blur', 'change']},
      { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' },
        { validator: (rule, value, callback) => {
            if (value !== data.form.password) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          }, trigger: 'blur'
        }
    ],
    role:[
      {required: true,message: '请选择角色',trigger:['blur', 'change']},
    ],
    phone:[
      {required: true,message: '请输入电话',trigger:['blur', 'change']},
      { pattern: /^1[3-9]\d{9}$/,
        message: '手机号应为11位数字（如：13800138000）'
      },
    ],
    email:[
      {required: true,message: '请输入邮箱',trigger:['blur', 'change']},
      { pattern: /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/,
        message: '请输入有效的邮箱（如：user@example.com）'
      },
    ],
  }
});

const formRef = ref()

//登录处理
const handleLogin = () => {
  router.push('/login')
};

//注册
const handleRegister = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/register', {
          username: data.form.username,
          password: data.form.password,
          role: data.form.role,
          email: data.form.email,
          phone: data.form.phone
        });

        // 检查响应中的 code 是否为 "200"
        if (res.code == "200") {
          ElMessage.success('注册成功');
          setTimeout(() => router.push('/login'), 1000);
        } else {
          ElMessage.error(res.msg || '注册失败');
        }
      } catch (err) {
        const errorData = err.response?.data;
        if (errorData) {
          // 处理后端返回的字段级错误（如 "username: 用户名已存在"）
          const [field, message] = errorData.msg?.split(':') || [];
          if (field && message) {
            ElMessage.warning(message.trim());
            formRef.value.validateField(field.trim());
          } else {
            ElMessage.error(errorData.msg || '注册失败');
          }
        } else {
          ElMessage.success('注册成功');
          setTimeout(() => router.push('/login'), 1000);
        }
      }
    }
  });
};




</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/bg.jpeg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-box {
  background-color: rgba(238, 250, 242, 0.85);
  width: 400px;
  padding: 30px 40px;
  border-radius: 10px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
}

.login-form {
  margin-top: 20px;
}

.login-btn {
  width: 48%;
  margin-top: 10px;
}

.el-select {
  width: 100%;
}
</style>